package edu.nlplab.mvc;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/")
public class FileManagementController {

    @Resource
    private HttpServletRequest request;

    @RequestMapping(value = "/preUpload", method = RequestMethod.GET)
    public String upload(ModelMap model) {
        return "uploadFiles";
    }

    @RequestMapping(value = "/uploadFiles", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Map<String, Object> addUploadFile(@RequestParam(value = "Filedata") MultipartFile file, HttpSession session) {

        String filePath = this.getFileUploadPath(session.getId());
        Map<String, Object> model = new HashMap<String, Object>();
        String originalFilename = file.getOriginalFilename();

        try {
            validateFileType(file);
            long now = System.currentTimeMillis();
            long filesize = file.getSize();
            long nameSuffix = now + filesize;
            String fileType = originalFilename.substring(originalFilename.lastIndexOf('.'));
            String fileNamePre = originalFilename.substring(0, originalFilename.lastIndexOf('.'));

            file.transferTo(new File(filePath + fileNamePre + "_" + nameSuffix + fileType));
        } catch (IOException e) {
            model.put("Code", 0);
            model.put("Msg", "文件[" + originalFilename + "]上传失败");
            e.printStackTrace();
            return model;
        } catch (Exception e) {
            model.put("Code", 0);
            model.put("Msg", e.getMessage());
            return model;

        }

        model.put("Code", 1);
        model.put("Msg", "文件上传成功");
        return model;
    }


    private void validateFileType(MultipartFile file) throws Exception {
        String[] allow = {".txt", ".log"};
        String originalFilename = file.getOriginalFilename();

        String fileType = originalFilename.substring(originalFilename.lastIndexOf('.'));
        if(Arrays.binarySearch(allow, fileType) < 0)
            throw new Exception("上传文件必须为Txt格式！");
    }

    // 获取文件路径
    private String getFileUploadPath(String sessionID) {
        String prePath = request.getSession().getServletContext().getRealPath("/") + "static/uploads/";
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String path = prePath + df.format(new Date()) + "/" + sessionID + "/";
        File dir = new File(path);
        // 如果文件夹不存在，则创建
        if (!dir.exists()) {
            //System.out.println(path);
            dir.mkdirs();
        }
        return path;
    }

}